var wechatMsgConstruct = require('./wechatMsgConstruct');
module.exports = function (req, res, next) {
    console.log('查看服务器列表');
    if (req.wechatMsg.MsgType == "text") {
        switch (true) {
            case /服务器/.test(req.wechatMsg.Content):
            case /节点/.test(req.wechatMsg.Content):
            case /节点列表/.test(req.wechatMsg.Content):
            case /服务器列表/.test(req.wechatMsg.Content):

                if(req.wechatUserStatus){
                    console.log('接受命令');
                    getNodeList(req, res, next);
                }else {
                    var chat = {
                        Type: "text",
                        Content: require('../config/config').unRegistered
                    };
                    // 最后一步需要信息,并关闭数据库连接
                    req.mysqlConnection.end();
                    res.send(wechatMsgConstruct(req.wechatMsg, chat));
                }

                break;
            default:
                next();
                break;
        }
    } else {
        next()
    }

    function getNodeList(req, res, next) {
        var nodeListStr = "服务器列表\n";
        var query = req.mysqlConnection.query("SELECT * FROM ss_node where status = 1");//炒作数据库
        query
            .on('error', function (err) {
                console.log('数据库连接失败', err)
            })
            .on('result', function (row) {
                req.mysqlConnection.pause();
                nodeListStr = "编号:" + row.id + "--" + row.name + "--IP:" + row.server + "\n";
                req.mysqlConnection.resume();

            })
            .on('end', function () {
                if(nodeListStr=="服务器列表\n"){
                    var chat = {
                        Type: "text",
                        Content:nodeListStr+"暂时无可用服务器\n"
                    };
                    // 最后一步需要信息,并关闭数据库连接
                    req.mysqlConnection.end();
                    res.send(wechatMsgConstruct(req.wechatMsg, chat));
                }else {
                    var chat = {
                        Type: "text",
                        Content:nodeListStr
                    };
                    // 最后一步需要信息,并关闭数据库连接
                    req.mysqlConnection.end();
                    res.send(wechatMsgConstruct(req.wechatMsg, chat));
                }
            });
    }

};